# coding:utf-8

from pydantic import BaseModel, Field
from typing import Optional
import pandas as pd
import time
from tabulate import tabulate

from utils.utils import time2str
from logger import logger

class BaseItem(BaseModel):
    name: str = Field(None, description="The name of the item")
    description: Optional[str] = Field(None, description="A brief description of the item")
    timestamp: int = int(time.time())
    filetype: str = Field(None, description="The type of the item")
    data: Optional[str] = Field(None, description="Data of Requesting")
    code_str: str = Field(None, description="Generate code of the item")

    def read_data(self):
        try:
            if self.filetype in ["txt"]:
                logger.info("file type: txt")
            elif self.filetype in ["csv", "xls", "xlsx"]:
                # 将 Markdown 表格转换为列表
                table = [line.split("|")[1:-1] for line in self.data.strip().split("\n")[1:]]
                logger.info(tabulate(table, headers="firstrow", tablefmt="pretty"))
                # 解析表格
                lines = self.data.strip().split("\n")
                headers = [header.strip() for header in lines[0].split("|")[1:-1]]
                data = []

                for line in lines[2:]:
                    row = [cell.strip() for cell in line.split("|")[1:-1]]
                    data.append(row)

                logger.info(f"Headers:{headers}")
                logger.info(f"Data:{data}")
                df = pd.DataFrame(data)
                df.columns = headers

                return df

            elif self.filetype in ["png"]:
                pass
        except Exception as e:
            raise Exception(f"read_data error: {str(e)}, time: {time2str(time.time())}")

